import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

// 定义处理compont组件的函数
// import layout from '@/layout/index.vue' === require('@/layout/index.vue').default
function loadView(conStr, name) {
  // console.log(conStr, 'constr')
  try {
    if (conStr === `/${name}`) {
      return require('@/layout/index.vue').default
    } else {
      return require('@/views' + conStr + '.vue').default
    }
  } catch (error) {
    return require('@/views/404.vue')
    // console.log(error)
  }
}

// 将平铺的数据转化为树形结构
function transListToTreeData(list, rootval) {
  const str = []
  list.forEach(item => {
    if (item.pid === rootval) {
      const children = transListToTreeData(list, item.id)
      if (children.length) item.children = children

      str.push(item)
    }
  })
  return str
}

router.beforeEach(async(to, from, next) => {
  // 动态设置网页标题
  // document.title = `优点达${to.meta.title}`
  // 也可以用封装好的函数实现
  document.title = getPageTitle(to.meta.title)

  NProgress.start() // 开进度条
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      // 判断是否已经有用户信息了,没有才获取
      if (!store.getters.userId) {
        // 跳转之前获取用户信息，调用actions里的函数
        const menuList = await store.dispatch('user/getInfoAction')
        console.log(menuList)

        const newRoutes = menuList.map(item => {
          return {
            path: item.path,
            name: item.name,
            meta: { title: item.title, icon: item.icon },
            redirect: '',
            hidden: item.status !== 1,
            component: loadView(item.path, item.name),
            pid: item.pid,
            id: item.id
          }
        })
        // console.log(newRoutes, 'newRoutes')
        const finallyRoutes = transListToTreeData(newRoutes, 0)
        console.log(finallyRoutes)
        finallyRoutes.forEach(item => {
          if (item.name === 'community') {
            item.children = [
              {
                path: '',
                name: 'communitySon',
                component: () => import('@/views/community'),
                meta: { title: '小区管理', icon: 'AppstoreOutlined' }
              }
            ]
          } else if (item.name === 'ticket') {
            item.children = [
              {
                path: '',
                name: 'ticketSon',
                component: () => import('@/views/ticket'),
                meta: { title: '投票管理', icon: 'AuditOutlined' }
              }
            ]
          }
        })
        // // 尾巴追加404的路由
        finallyRoutes.push({ path: '*', redirect: '/404', hidden: true })
        // // 渲染左侧菜单
        await store.dispatch('menus/acceptRoutes', finallyRoutes)
        // // 动态添加路由
        router.addRoutes(finallyRoutes)
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
